<script setup>
/**
 * & 文件引入区域
 */
import { ToastFun } from "@/hook/toast";
import { useUseStore } from "@/stores/user";
import { useRoute, useRouter } from "vue-router";
import { onBeforeMount, onUnmounted, reactive, ref } from "vue";

import {
  upLoadImg,
  getDealDetail,
  upLoadPointBalance,
  getTraditionDetail,
  confirmTransaction,
  generateTradeOrder,
} from "@/server/api/userInfo";
import { exchange } from "@/stores/exchange";
import { getJWTFun } from "@/hook/jsrsasign";
import { useI18n } from "vue-i18n";
import { showToast } from 'vant';

const { t } = useI18n();
/**
 * & 变量声明区
 */
const route = useRoute();
const router = useRouter();
let tradinId = ref(); // 接收订单id
let orderData = ref(); // 订单详情数据
let socket = null; // 准备进行长连接的变量
let baseUrl = useUseStore().ing; // 图片拼接基础路径
let isShow = ref(false); // 用于控制长连接前后页面的显示隐藏

// 交易提交请求体
let upLoadReq = reactive({
  typeId: "",
  orderId: "",
  piAddress: "",
  buyerId: useUseStore().userId,
});

let formData = null; // 上传交易凭证的图片数据
let imgList = ref(); // 上传的图片回显

let regex = /^(?!\s+$).+$/; // 交易地址正则匹配

//屏蔽层图片
const showPic = ref(false);

/**
 * & 函数区
 */
// 获取订单详情方法
const getTraditionDetailFun = async () => {
  // 轻提示，等待数据请求和长连接成功后再关闭提示
  ToastFun("Loading", { duration: 1000 });
  let { data } = await getTraditionDetail(tradinId.value);

  if (data.data != null) {
    ToastFun("", {});
    isShow.value = true;

    orderData.value = data.data;

    // 生成请求体
    for (const i in upLoadReq) {
      if (i in orderData.value) {
        upLoadReq[i] = orderData.value[i];
      }
    }
  } else {
    // 获取不到值则说明该交易已经有人在进行，直接退出该页面并提示
    ToastFun("", { msg: t(pay.fail2) });
    router.back();
  }

};

// 交易双方获取交易详情
const getDealDetailFun = async () => {
  ToastFun("Loading", { duration: 1000 });
  let { data } = await getDealDetail(tradinId.value);

  if (data.code == 200) {
    ToastFun("close", {});
    isShow.value = true;

    // 解构获取需要的对应数据
    let {
      typeId,
      status,
      imageUrl,
      sellerId,
      piBalance,
      piAddress,
      buyerName,
      sellerName,
      buyerImageUrl,
      sellerImageUrl,
      pointBalance,
    } = data.data;

    // 修改请求体
    upLoadReq.piAddress = piAddress;
    upLoadReq.orderId = tradinId.value;
    upLoadReq.typeId = typeId;

    orderData.value = {
      status,
      typeId,
      imageUrl,
      sellerId,
      piAddress,
      piBalance,
      pointBalance,
      userImage:
        sellerId == useUseStore().userId ? buyerImageUrl : sellerImageUrl,
      userName: sellerId == useUseStore().userId ? buyerName : sellerName,
    };

  } else {
    ToastFun("", {});
    router.back();
  }
};

// 提交订单方法
const submit = () => {
  generateTradeOrderFun(); // 生成订单
};

// 生成订单
const generateTradeOrderFun = async () => {

  ToastFun("Loading", { duration: 1000 });

  // 发起请求
  let { data } = await generateTradeOrder(tradinId.value,useUseStore().userId);
  console.log(data);
  if (data.code == 200) {
      showToast('请点击右上角头像，进入订单完成流程');
      setTimeout(() => {
        router.go(-1);
      }, 1000)
    } else {
      ToastFun(t("pay.fail2"), {})
  }
};

// 提交转积分
const upPointFun = async () => {
  ToastFun(t("hotelPage.message"), { duration: 1000 });

  let token = getJWTFun(upLoadReq); // 生成tokken
  let { data } = await upLoadPointBalance(token); // 请求接口

  if (data.code == 200) {
    // 提示交易成功，并且返回上一级
    ToastFun("", {});
    getDealDetailFun();
  } else {
    ToastFun("", {});
  }
};

// 提交pi币转账凭证
const upLoadImgFun = async () => {
  if (formData != null) {
    let { typeId, orderId } = upLoadReq;

    let Req = {
      typeId,
      orderId,
      userId: useUseStore().userId,
    };

    // 轻提示
    ToastFun("Loading", { duration: 1000 });
    let token = getJWTFun(Req); // 生成tokken
    let { data } = await upLoadImg(token, formData); // 请求接口

    if (data.code == 200) {
      ToastFun("", {});

      // 判断如果是卖家确认要上传pi支付凭证，则重新请求数据
      if (exchange().orderType == "comfirm") {
        // 重新获取该订单详情
        getDealDetailFun();
      } else if (exchange().orderType == "transaction") {
        router.back();
      }
    } else {
      ToastFun("", {});
    }
  } else {
    ToastFun("show", { msg: t("exchangeOrder.pic") });
  }
};

// 确认交易
const confirmTransactionFun = async () => {
  ToastFun("Loading", { duration: 1000 });

  // 生成token
  let token = getJWTFun({
    userId: useUseStore().userId,
    orderId: tradinId.value,
  });

  // 请求接口
  let { data } = await confirmTransaction(token);

  if (data.code == 200) {
    ToastFun("", {});

    // 成功后重新获取订单详情
    getDealDetailFun();

  } else {
    ToastFun("", {});
  }
};

// 获取图片
const getImg = (file) => {
  // 转换表单格式
  formData = new FormData();
  formData.append("file", file.file);
};

// 图片超过上传大小限制提示
const onOversize = () => {
  ToastFun("show", { msg: t("exchangeOrder.over") });
};

// 生命周期
onBeforeMount(() => {
  tradinId.value = route.query.id; // 获取订单id
  if (exchange().orderType == "transaction") {
    getTraditionDetailFun(); // 获取订单详情方法
  } else if (exchange().orderType == "comfirm") {
    getDealDetailFun(); // 交易双方获取交易详情
  }
});

onUnmounted(() => {
  // 退出页面关闭socket
  if (socket != null) {
    socket.close();
  }
});
</script>

<template>
  <div class="ExchangeOrderPage" v-if="isShow">
    <div class="top">
      <ExchangeOrderTop :title="$t('exchange.trade')" />
    </div>

    <div class="content" v-if="orderData">
      <div class="user">
        <img :src="orderData.userImage || '/images/pipayshop_logo.png'" alt="" />
        <div class="name">{{ orderData.userName }}</div>
      </div>

      <!-- 交易面板 从对方获得/需向对方支付 -->
      <div class="form">
        <div class="item to">
          <div class="title">
            {{
    (orderData.typeId == 2 && orderData.sellerId == useUseStore().userId) ||
      (orderData.typeId == 3 && orderData.sellerId != useUseStore().userId)
      ? $t("exchange.tips1")
      : $t("exchange.tips2")
  }}
          </div>
          <div class="num">
            <div class="title">eCNY</div>
            <span>{{ orderData.pointBalance }}</span>
          </div>
        </div>

        <div class="item from">
          <div class="title">
            {{
    (orderData.typeId == 2 && orderData.sellerId != useUseStore().userId) ||
      (orderData.typeId == 3 && orderData.sellerId == useUseStore().userId)
      ? $t("exchange.tips1")
      : $t("exchange.tips2")
  }}
          </div>
          <div class="num">
            <div class="title"> Currency</div>
            <span>￥{{ orderData.piBalance }}</span>
          </div>
        </div>
      </div>
      <!-- 提交积分、提交凭证 操作 -->
      <div class="address" v-if="exchange().orderType == 'comfirm' && orderData.status < 2">
        <!-- <div class="title" v-if="orderData.status < 2"> -->
        <div class="title">
          任意选一种支付
        </div>
        <div type="text">
          <img src="/images/paymentCode/weChatPaySign.png" style="width: 90px;height: 60px;"><br />
          <img style="width: 60px;height: 70px;" src="/images/paymentCode/we_chat_pay.jpg" @click="showPic = true">
        </div>
        <div>
          <img src="/images/paymentCode/payPalSign.jpg" style="width: 60px;height: 20px;"><br />
          <van-icon name="contact-o" size="40" />lituanpeng@gmail.com
        </div>
      </div>
      <!-- 交易凭证上传框 -->
      <div class="voucher" v-if="orderData.status == 0 && exchange().orderType == 'comfirm'">
        <div class="title" v-if="(orderData.typeId == 2 &&
    orderData.sellerId != useUseStore().userId) ||
    (orderData.typeId == 3 && orderData.sellerId == useUseStore().userId)
    ">
          {{ $t("exchange.certificate") }}
        </div>
        <!-- 这里取反的意思是要保证&&一整条都是true，空就要上传，但是空是false,所以要取反 -->
        <van-uploader :max-count="1" v-model="imgList" :after-read="getImg" @oversize="onOversize"
          @delete="formData = null" :max-size="1000 * 1024" v-if="(orderData.typeId == 2 &&
    orderData.sellerId != useUseStore().userId &&
    !orderData.imageUrl) ||
    (orderData.typeId == 3 &&
      orderData.sellerId != useUseStore().userId &&
      !orderData.imageUrl)">
          <div class="updata">
            <img src="/images/Me/updataLogo.png" alt="" class="icon" />
            <span>Photos</span>
          </div>
        </van-uploader>
        <!-- 这个是提交什么出现的问题是吗？被隐藏了 -->
        <div class="question" v-if="false">
          <textarea name="" id="" cols="30" rows="5" :placeholder="$t('exchangeOrder.issuse')" />
          <van-uploader>
            <div class="updata">
              <img src="/images/Me/updataLogo.png" alt="" class="icon" />
              <span>Photos</span>
            </div>
          </van-uploader>
        </div>
      </div>

      <!-- 交易凭证图片 -->
      <div class="img" v-if="orderData.imageUrl">
        <div class="title">{{ $t("exchange.certificate") }}</div>
        <img style="width: 311px;height:652px ;object-fit: contain;" :src="orderData.imageUrl" />
      </div>
    </div>
    <!-- 进来默认是要用户按确认 -->
    <div class="submit" @click="submit" v-if="exchange().orderType == 'transaction'">
      {{ $t("exchange.confirm") }}
    </div>
    <!--   -->
    <div class="submit" @click="orderData.sellerId == useUseStore().userId ? upPointFun() : ''"
      v-if="orderData.status == 0 && exchange().orderType == 'comfirm'">
      {{
    orderData.sellerId == useUseStore().userId
      ? $t("exchange.submit1")
      : $t("exchange.waiting1")
  }}
    </div>

    <!-- submit2上传支付凭证 waIting2等待对方上传支付凭证 -->
    <div class="submit" @click="
    (orderData.typeId == 2 && orderData.sellerId != useUseStore().userId) ||
      (orderData.typeId == 3 && orderData.sellerId == useUseStore().userId)
      ? upLoadImgFun()
      : ''
    " v-if="orderData.status == 0 && exchange().orderType == 'comfirm'">
      {{
    (orderData.typeId == 2 && orderData.sellerId != useUseStore().userId) ||
      (orderData.typeId == 3 && orderData.sellerId == useUseStore().userId)
      ? $t("exchange.submit2")
      : $t("exchange.waiting2")
  }}
    </div>
    <!--confirm确认 waiting3等待对方确认交易  -->
    <div class="submit" v-if="orderData.status == 2 && exchange().orderType == 'comfirm'" @click="
    (orderData.typeId == 2 && orderData.sellerId == useUseStore().userId) ||
      (orderData.typeId == 3 && orderData.sellerId != useUseStore().userId)
      ? confirmTransactionFun()
      : ''
    ">
      {{
    (orderData.typeId == 2 && orderData.sellerId == useUseStore().userId) ||
      (orderData.typeId == 3 && orderData.sellerId != useUseStore().userId)
      ? $t("exchange.confirm")
      : $t("exchange.waiting3")
  }}
    </div>
    <!-- 订单完成 -->
    <div class="submit" v-if="orderData.status == 3 && exchange().orderType == 'comfirm'">
      {{ $t("exchange.waiting4") }}
    </div>
    <!-- 图片展示屏蔽层 -->
    <van-overlay :show="showPic" @click="showPic = false">
      <div class="wrapper">
        <div class="block">
          <img style="width: 100%;" src="/images/paymentCode/we_chat_pay.jpg">
        </div>
      </div>
    </van-overlay>
  </div>
</template>

<style lang="scss" scoped>
.ExchangeOrderPage {
  position: relative;
  min-height: 100vh;
  max-height: 100vh;
  overflow: scroll;

  &::-webkit-scrollbar {
    display: none;
  }

  >.content {
    padding: 24rem 16rem 80rem;

    >.user {
      display: flex;
      align-items: center;

      margin-bottom: 16rem;

      >img {
        width: 34rem;
        margin-right: 6rem;
      }

      >.name {
        color: #333;
        font-size: 16rem;
        font-weight: 500;
        line-height: 22rem;
      }
    }

    >.form {
      position: relative;

      >.item {
        margin-bottom: 24rem;

        >.title {
          font-size: 14rem;
          font-weight: 400;
          line-height: 20rem;
          color: #333;
          margin-bottom: 24rem;
        }

        >.num {
          line-height: 44rem;
          font-size: 32rem;
          font-weight: 500;

          display: flex;

          >.title {
            color: rgba(100, 46, 142, 1);
            margin-right: 10rem;
          }

          >span {
            color: rgba(51, 51, 51, 1);
          }
        }

        &.from {
          >.num .title {
            font-size: 16rem;
            font-weight: 400;
            line-height: 44rem;
          }
        }
      }
    }

    >.address {
      font-size: 16rem;
      font-weight: 400;
      line-height: 22rem;

      >div {
        margin-bottom: 16rem;
      }

      >input {
        width: 100%;
        border-bottom: 1rem solid #f0f0f0;
      }
    }

    >.voucher {
      font-size: 16rem;
      font-weight: 400;
      line-height: 22rem;

      >.title {
        margin-bottom: 24rem;
      }

      >.question {
        position: relative;
        border-radius: 16rem;
        padding: 12rem;
        background: #f5f5f5;

        >textarea {
          width: 100%;
          border: 0;
          background: transparent;
        }
      }

      .updata {
        width: 64rem;
        height: 64rem;

        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        font-size: 14rem;
        line-height: 20rem;
        color: rgba(255, 255, 255, 1);

        border-radius: 4rem;
        background: #ccc;

        >img {
          width: 14rem;
        }
      }
    }

    >.img {
      width: 100%;

      >.title {
        font-size: 16rem;
        font-weight: 400;
        line-height: 22rem;
        margin-bottom: 16rem;
      }

      img {
        width: 100%;
      }
    }
  }

  >.submit {
    position: fixed;
    bottom: 16rem;
    left: 0;
    right: 0;

    display: flex;
    justify-content: center;
    margin: 0 16rem;
    padding: 15rem 0;
    background: #642e8e;
    border-radius: 26rem;

    font-size: 16rem;
    font-weight: 500;
    line-height: 22rem;
    color: #fff;
  }

  .wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }

  .block {
    width: 75%;
    background-color: #fff;
  }
}
</style>
